import router from '@/router'
import { useToken } from '@/stores/token'
import type { ResponseResult } from '@/types/common'
import axios, { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_URL,
  timeout: 5000
})

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const store = useToken()
  if (store.getToken()) {
    config.headers.Authorization = store.getToken()
  }
  return config
}, error => Promise.reject(error))

instance.interceptors.response.use((response: AxiosResponse) => {
  const result = response.data
  if (result.code === 10000) {
    return result.data
  }
  ElMessage({
    message: result.msg
  })
  return Promise.reject(new Error(result.msg))
}, (error: AxiosError) => {
  if (error.status === 401) {
    const store = useToken()
    store.removeToken()
    router.push('/')
  }
  const res = error.response?.data as ResponseResult
  ElMessage({
    message: res.msg,
    type: 'error'
  })
  return Promise.reject(error)
})

export default class RequestAxios {
  static get<T>(url: string, params?: object) {
    return instance.get<null, T>(url, { params })
  }
  static post<T = null>(url: string, data?: object) {
    return instance.post<null, T>(url, data)
  }
  static delete<T>(url: string, params?: object) {
    return instance.delete<null, T>(url, { params })
  }
  static put<T>(url: string, data?: object) {
    return instance.put<null, T>(url, data)
  }

}